package utils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import bean.Files;
import bean.Folders;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

public class FileDataUtils {
    private static final String STORAGE_FILE = "file_data.json";
    private List<Files> fileList = new ArrayList<>();
    private ObjectMapper objectMapper = new ObjectMapper();
    
    public void test() {
    	System.out.println("---@AutoWired---test---test---");
    }
    // 加载数据
    public List<Files> loadData() {
        try {
            File file = new File(STORAGE_FILE);
            if (file.exists()) {
                fileList = objectMapper.readValue(file, new TypeReference<List<Files>>() {});
            }
        } catch (IOException e) {
            System.err.println("加载数据失败: " + e.getMessage());
            fileList = new ArrayList<>();
        }
        return fileList;
    }
    
    // 保存数据（格式化输出，带换行和缩进）
    public void saveData() {
        try {
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(STORAGE_FILE), fileList);
        } catch (IOException e) {
            System.err.println("保存数据失败: " + e.getMessage());
        }
    }
    
    // 增删改查方法
    public void addFile(Files file) {
        fileList.add(file);
        saveData();
    }
    
    public boolean removeFile(String fileName) {
        boolean removed = fileList.removeIf(f -> f.getFileName().equals(fileName));
        if (removed) saveData();
        return removed;
    }
    
    public boolean updateFile(String filename) {
    	loadData();
        for (int i = 0; i < fileList.size(); i++) {
            if (fileList.get(i).getFileName().equals(filename)) {
                fileList.get(i).setFileName(filename);
                saveData();
                return true;
            }
        }
        return false;
    }
    
    public Files findFileByPath(String filePath) {
        return fileList.stream()
            .filter(f -> f.getFilePath().equals(filePath))
            .findFirst()
            .orElse(null);
    }
    
    public List<Files> getAllFiles() {
        return new ArrayList<>(fileList); // 返回副本保护原始数据
    }
    
    
}